<template>
    <!-- 城市地图标注 -->
    <div class="city-map-mark-wrap">
        <el-row>
            <el-col :span="5">
                <el-form :model="markInfoForm" :rules="markInfoFormRules" ref="markInfoForm" @submit.native.prevent>
                    <el-form-item label="业主单位：" prop='organizationId'>
                        <el-select filterable v-model="markInfoForm.organizationId">
                            <el-option
                                v-for="item in orgList"
                                :key="item.organizationId"
                                :label="item.shortName"
                                :value="item.organizationId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="打点类型：" prop='markType'>
                        <el-select v-model="markInfoForm.markType">
                            <el-option
                                v-for="item in markTypeList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="bindLabelTxt" prop='markObjectId'>
                        <el-select v-if="markInfoForm.markType != 2" filterable v-model="markInfoForm.markObjectId">
                            <el-option
                                v-for="item in bindList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                        <tree-select
                            v-else
                            v-model="markInfoForm.markObjectId"
                            placeholder="请选择建筑物"
                            filterable
                            :width="366"
                            :data="buildList"
                            :defaultProps="buildDefaultProps"
                            :checkedKeys="defaultCheckedBuildId"
                            :nodeKey="buildNodeKey">
                        </tree-select>
                    </el-form-item>
                    <el-form-item label="经度：" prop='lon'>
                        <el-input type="number" v-model="markInfoForm.lon" ></el-input>
                    </el-form-item>
                    <el-form-item label="纬度：" prop='lat'>
                        <el-input type="number" v-model="markInfoForm.lat"></el-input>
                    </el-form-item>
                    <el-form-item >
                        <el-row type="flex" justify="end">
                            <el-button class="form-search-btn" type="primary" @click="clearLonLat">清空</el-button>
                            <el-button class="form-search-btn" type="primary" :disabled="saveBtnDisabled" @click="saveMarkInfo('markInfoForm')">保存</el-button>
                        </el-row>
                    </el-form-item>
                </el-form>
            </el-col>
            <el-col :span="18" :offset="1">
                <!-- 地图 -->
                <div>
                    <el-row type="flex" justify="start">
                        <h3 style="height: 50px;line-height: 50px;margin-right: 20px;">地图</h3>
                        <!-- <img v-if="logoUrl!=''" :src="logoUrl" width="40px" height="40px"> -->
                    </el-row>
                    <bmap-model ref="bMap" v-on:newMarkPoint="newMarkPoint"></bmap-model>
                </div>
                <!-- 列表 -->
                <div>
                    <el-row style="margin-bottom: 15px;margin-top: 15px;">
                        <h3>标注列表</h3>
                    </el-row>
                    <!-- <el-row>
                        <el-form :inline="true" :model="searchForm" class="demo-form-inline" @submit.native.prevent>
                            <el-form-item>
                                <el-input
                                    placeholder="名称"
                                    v-model="searchForm.markName"
                                    @keyup.enter.native="getTableData"
                                    clearable>
                                </el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button class="form-search-btn" type="primary" @click="getTableData">查询</el-button>
                            </el-form-item>
                        </el-form>
                    </el-row> -->
                    <el-table
                        v-loading="loading"
                        ref="markTableList"
                        :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)"
                        style="width: 100%">
                        <el-table-column label="序号" type="index" width="50"></el-table-column>
                        <el-table-column label="名称" prop="markName"></el-table-column>
                        <el-table-column label="经度" prop="lon"></el-table-column>
                        <el-table-column label="纬度" prop="lat"></el-table-column>
                        <el-table-column label="操作" width="150">
                            <template slot-scope="scope">
                                <el-button @click="showPoint(scope.row.lon, scope.row.lat, scope)" type="text" size="small">定位</el-button>
                                <span class="dividing-line">|</span>
                                <el-button @click="deleteMark(scope.row)" type="text" size="small">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- 分页 -->
                    <el-pagination
                        background
                        layout="total, prev, pager, next, jumper"
                        :total="total"
                        @current-change="currentChange">
                    </el-pagination>
                </div>
            </el-col>
        </el-row>
    </div>
</template>
<script>
import TreeSelect from '@/libs/TreeSelect/Main'
import bmapModel from './Pagemodel/BMap'
import { getOrgList } from '@/api/org'
import { getFbsTree } from '@/api/fbs'
import util from '@/utils/util'
import { getMapsMarkersByType, getListForMap, getMarkRelatFcfInfo, saveMapMarkExt, delMapsMakers } from '@/api/sysConfig'

export default {
    name: 'CityMapMark',
    components: {
        TreeSelect,
        bmapModel
    },
    data() {
        return {
            loading: false,
            saveBtnDisabled: true,
            orgList: [],
            markTypeList: [], // 打点类型选项
            bindLabelTxt: '关联联网单位', // 关联信息label文案
            bindList: [], // 关联信息数据
            buildList: [],
            buildDefaultProps: {
                children: 'nodes',
                label: 'text',
                value: 'id'
            },
            buildNodeKey: 'id',
            defaultCheckedBuildId: [],
            markInfoForm: {
                id: '',
                organizationId: '',
                markType: 1,
                markObjectId: '', // 关联业主单位
                lon: '',
                lat: '',
            },
            markInfoFormRules: {
                lon: [
                    { required: true, message: '请输入经度', trigger: 'blur' }
                ],
                lat: [
                    { required: true, message: '请输入纬度', trigger: 'blur' }
                ]
            },
            searchForm: {
                markName: ''
            },
            logoUrl: '', // logo图片
            tableData: [], // 地图标注列表信息
            total: 0,
            pagesize: 10,
            currentPage: 1
        }
    },
    created() {
        let that = this
        // 获取业主单位信息
        getOrgList({
            queryType: 0
        }).then(res => {
            if(res.status = 200) {
                that.orgList = res.data
                // 初始选中第一个单位
                that.markInfoForm.organizationId = res.data[0].organizationId
                // 获取地图标注点信息
                that.getMapMarkInfo()
                // 加载列表
                that.getTableData()
            }
        })
        // 获取打点类型
        util.ilinkArrHandle.delDicArr_keyVal(70, (arr) => {
            that.markTypeList.push.apply(that.markTypeList, arr)
        })
    },
    methods: {
        // 获取关联数据
        getBindData() {
            let that = this
            if(that.markInfoForm.markType == 2) {
                // 建筑物单独请求接口
                getFbsTree({
                    organizationId: that.markInfoForm.organizationId
                }).then(res => {
                    if(res.status === 200 && res.data.length > 0) {
                        that.buildList = res.data
                        // 默认选择第一个
                        that.markInfoForm.markObjectId = res.data[0].id
                        that.$nextTick(() => {
                            that.defaultCheckedBuildId.push(res.data[0].id)
                        })
                        // 保存按钮启用
                        that.saveBtnDisabled = false
                    } else {
                        that.buildList = []
                        that.markInfoForm.markObjectId = ''
                        that.$message({
                            type: 'warning',
                            message: `当前没有关联的${that.bindLabelTxt.replace('关联', '').replace('：', '')}，请先录入数据`
                        })
                        // 保存按钮禁用
                        that.saveBtnDisabled = true
                    }
                })
            } else {
                getMarkRelatFcfInfo({
                    orgId: that.markInfoForm.organizationId,
                    type: that.markInfoForm.markType
                }).then(res => {
                    if(res.status === 200) {
                        that.bindList = res.data
                        // 没有关联数据
                        if(res.data.length > 0) {
                            // 默认选择第一个
                            that.markInfoForm.markObjectId = res.data[0].id
                            // 保存按钮启用
                            that.saveBtnDisabled = false
                        } else {
                            that.markInfoForm.markObjectId = ''
                            that.$message({
                                type: 'warning',
                                message: `当前没有关联的${that.bindLabelTxt.replace('关联', '').replace('：', '')}，请先录入数据`
                            })
                            // 保存按钮禁用
                            that.saveBtnDisabled = true
                        }
                    }
                })
            }
        },
        // limit(e){  
        //     var keynum=window.event ? e.
        // },
        // 百度地图初始化
        bMapInit() {
            let that = this
        
            that.$refs['bMap'].clearMarkPoint()
            that.$refs['bMap'].initMap()
            that.getMapMarkInfo()
        },
        // 获取地图打点信息
        getMapMarkInfo() {
            let that = this
            getListForMap({organizationIds: that.markInfoForm.organizationId}).then(res => {
                if(res.status === 200) {
                    // 显示logo
                    that.logoUrl = res.data[0].logoUrl
                    // 调用地图组件中的打点方法
                    that.$refs['bMap'].addMarker(res.data[0].longitude, res.data[0].latitude)
                }
            })
        },
        // 清空经纬度
        clearLonLat() {
            let that = this
            that.markInfoForm.lon = ''
            that.markInfoForm.lat = ''
        },
        // 保存
        saveMarkInfo(formName) {
            // 阻止事件冒泡
            event.stopPropagation()
            let that = this
            let parames = {}
            // 校验表单
            that.$refs[formName].validate((valid) => {
                if(valid) {
                    parames = {
                        id: 0,
                        organizationId: that.markInfoForm.organizationId,
                        markType: that.markInfoForm.markType,
                        markObjectId: that.markInfoForm.markObjectId,
                        lon: that.markInfoForm.lon,
                        lat: that.markInfoForm.lat,
                        markName:  that.searchForm.markName.trim(),
                    }
                    saveMapMarkExt(parames).then(res => {
                        if(res.status === 200) {
                            if(res.data == 0) {
                                that.$message({
                                    message: '保存成功！',
                                    type: 'success'
                                })
                            } else {
                                that.$message({
                                    message: '标注重复！',
                                    type: 'warning'
                                })
                            }

                            // 清除经纬度
                            that.clearLonLat()
                            that.$refs['bMap'].saveSuccess()
                            that.bMapInit()
                            // 刷新列表
                            that.getTableData()
                        } else {
                            that.$message({
                                message: '保存失败！',
                                type: 'warning'
                            })
                        }
                    })
                } else {
                    return false
                }
            })
        },
        // 获取地图标注列表信息
        getTableData() {
            let that =this
            let parames = {
                orgIds: that.markInfoForm.organizationId,
                markTypes: that.markInfoForm.markType,
                markName: that.searchForm.markName.trim(),
                order: 'desc',
                offset: 0,
                limit: 10
            }

            getMapsMarkersByType(parames).then(res => {
                if(res.status === 200) {
                    that.tableData = res.data
                    that.total = res.total
                    // 调用地图组件中的清楚标记点方法
                    that.$refs['bMap'].clearMarkPoint()
                    // 调用地图组件中的设置地图标注点信息方法
                    that.$refs['bMap'].setMapMarkInfo(that.markInfoForm.markType, res.data)
                }
            })
        },
        // 获取经纬度
        newMarkPoint(lon, lat) {
            let that = this
            that.markInfoForm.lon = lon
            that.markInfoForm.lat = lat
        },
        currentChange(currentPage) {
            this.currentPage = currentPage;
        },
        // 定位
        showPoint(lon, lat, scope) {
            var that = this
            // 调用地图组件中的定位方法
            that.$refs['bMap'].showPoint(lon, lat, scope)
        },
        // 删除
        deleteMark(row) {
            let that = this
            if (row) {
                that.$confirm('确定要删除吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    roundButton: true
                }).then(() => {
                    // 调用删除接口
                    delMapsMakers({
                        id: row.id
                    }).then(res => {
                        if( res.status === 200) {
                            that.$message({
                                type: 'success',
                                message: '操作成功!'
                            })
                            that.bMapInit()
                            // 刷新列表
                            that.getTableData()
                        }else{
                            that.$message.error(res.info)
                        }
                    })
                }).catch(() => {
                })
            }
        },
        // 映射关联字段label名称
        mapBindLabel(id) {
            let that = this
            let list = that.markTypeList

            for(var i=0, len=list.length; i < len; i++) {
                if(id == list[i].id) {
                    that.bindLabelTxt = '关联' + list[i].name + '：'
                    break
                }
            }
        }
    },
    watch: {
        // 监听业主单位值变化
        orgIdSelect(val, oldVal) {
            if(val !== oldVal) {
                // 重新获取关联
                this.getBindData()
                // 重新获取列表
                this.getTableData()
            }
        },
        // 监听打点类型变化
        markTypeSelect(val, oldVal) {
            if(val !== oldVal) {
                // 映射关联字段label名称
                this.mapBindLabel(val)
                // 重新获取关联
                this.getBindData()
                // 重新获取列表
                this.getTableData()
            }
        },
    },
    computed: {
        orgIdSelect() {
            return this.markInfoForm.organizationId
        },
        markTypeSelect() {
            return this.markInfoForm.markType
        },
    }
}
</script>
